import uuid

from src.util.CaptchaUtil import get_code, create_captcha
from src.entry.Entrys import Captcha
from src.util.JwtUtil import createToken
from src.util.Service import *
from src.util.PwdUtil import createHashPwd
from src.util.Cache import cache

""" 验证码信息缓存 """

""" 获取验证码 """


def getCaptcha(timeout):
    code = get_code(6)
    img = create_captcha(code, 150, 60, 25, noise_points=320)
    token = str(uuid.uuid4())
    # print(f"\"code\":\"{code}\",\n\"token\":\"{token}\"")
    cache.set(token, code, timeout)
    return Captcha(img=img, token=token).__dict__


""" 验证验证码 """


def authCaptcha(token, code: str, login=False) -> bool | None:
    # time 单位为分钟
    captcha_cfg: dict = Config.getConfigByKey('##Captcha', 'public')
    if login and captcha_cfg and captcha_cfg.get('value') == 'off':
        return True
    try:
        baseCode = cache.get(token)
        if baseCode is None:
            return None
        cache.delete(token)
        # print(codeinfo.initTime + time,now)
        if baseCode.lower() == code.lower():
            return True
    except:
        return False
    return False


""" 登陆 """


def signIn(uname, pwd: str):
    info = User.hasUserByUP(uname, createHashPwd(uname, pwd))
    if info is None:
        return 0
    elif info['status'] == '0':
        return 1
    pld = {
        'id': info['uId'],
        'username': info['username'],
        'initTime': info['initTime'],
        'exceedTime': datetime.now(UTC) + timedelta(minutes=30)
    }
    return createToken(pld)


""" 注册 """


def signUp(form: dict):
    u = form.get('username')
    cfg: dict = Config.getConfigByKey('##register', 'sys')
    if cfg and cfg.get('value') == 'off':
        return 3
    if User.getUserByUsername(u):
        return 0
    form['password'] = createHashPwd(u, form.get('password'))
    form['initTime'] = datetime.now(UTC)
    form['status'] = '1'
    form['head'] = 'User'
    User.addUser(form)
    return 1


def hasUser(username):
    return User.hasUserByUsername(username)


def roleSignIn(uid: int, rid: int):
    if not UserRole.hasUserRole(uid, rid):
        return False
    user = User.getUserById(uid)
    exceedTime = Config.getConfigByKey('##tokenExceedTime', 'sys')
    if exceedTime:
        exceedTime = int(exceedTime.get('value'))
    else:
        exceedTime = 30
    if user.get('status') != '1':
        return False
    if Role.getRoleStatus(rid) != '1':
        return False
    return createToken({
        'id': uid,
        'rid': int(rid),
        'username': user.get('username'),
        'nickname': user.get('nickname'),
        'exceedTime': datetime.now(UTC) + timedelta(minutes=exceedTime)
    })


def test(k):
    return cache.get(k)
